package com.shareware.common.memory.entity

import com.shareware.common.memory.MemoryHelper
import com.shareware.common.utils.safeLet
import org.json.JSONObject

/**
 * desc: 功能描述
 * email: mobiledeveloper@qq.com
 */
data class JavaMemInfo(
    val heapSizeByte: Long = Runtime.getRuntime().totalMemory(),
    val recycledByte: Long = Runtime.getRuntime().freeMemory(),
    val usedByte: Long = heapSizeByte - recycledByte,
    val maxByte: Long = Runtime.getRuntime().maxMemory(),
    val memClass: Int = MemoryHelper.memClass,
    val largeMemClass: Int = MemoryHelper.largeMemClass,
) {
    override fun toString(): String {
        return String.format(
            "%-21s %-21s %-21s %-21s %-21s %-21s",
            "Used=$usedByte B",
            "Recycled=$recycledByte B",
            "HeapSize=$heapSizeByte B",
            "Max=$maxByte B",
            "MemClass:$memClass M",
            "LargeMemClass=$largeMemClass M"
        )
    }

    fun toJson() = safeLet(defVal = JSONObject()) {
        JSONObject().apply {
            put("used", usedByte)
            put("recycled", recycledByte)
            put("heapSize", heapSizeByte)
            put("max", maxByte)
            put("memClass", memClass)
            put("largeMemClass", largeMemClass)
        }
    }
}